<script setup lang="ts">
import { ref, markRaw, shallowRef, computed } from "vue";
import { useColumns } from "./cloud_columns";
import Plus from "~icons/ep/plus";
import Delete from "~icons/ep/delete";
import UploadIcon from "~icons/ri/upload-2-line?width=26&height=26";
import "plus-pro-components/es/components/dialog-form/style/css";
import { getProductInfo, setProductInfo, addProductInfo } from "@/api/finance";
import {
  fixImageUrl,
  handleImagesUpload,
  handleImagesUploadEditor
} from "@/utils/common";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import {
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import {
  type Action,
  genFileId,
  ElMessageBox,
  ElMessage,
  UploadInstance,
  UploadProps,
  UploadRawFile
} from "element-plus";
import { deviceDetection } from "@pureadmin/utils";
const isMobile = deviceDetection();
const previewImageUrl = ref();
const previewImageName = ref();
const showPreviewImage = ref(false);
const edit = ref(false);

const productImageRef = ref<UploadInstance>();
const productJSImageRef = ref<UploadInstance>();

const mode = isMobile ? "simple" : "default";
const editorRef = shallowRef();
const toolbarConfig: any = {}; // { excludeKeys: "fullScreen" };
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file: File, insertFn) => {
        try {
          const res = await handleImagesUploadEditor(file);
          insertFn(res.data, "", res.data);
        } catch (error) {
          console.error(error);
        }
      }
    },
    insertVideo: {
      onInsertedVideo: async video => {
        if (video == null) return;
      }
    },
    uploadVideo: {
      customUpload: async (file: File, insertFn) => {
        try {
          const res = await handleImagesUploadEditor(file);
          insertFn(res.data, "");
        } catch (error) {
          console.error(error);
        }
      }
    }
  }
};
const handleCreated = editor => {
  // 记录 editor 实例，重要！
  editorRef.value = editor;
};

const rules = {
  title: [
    {
      required: false,
      message: "商品标题必填"
    }
  ],
  iconimage: [
    {
      required: false,
      message: "商品图片必填"
    }
  ],
  images: [
    {
      required: false,
      message: "介绍图片必填"
    }
  ]
};

const formColumns: PlusColumn[] = [
  {
    label: "商品标题",
    width: 120,
    prop: "title",
    valueType: "input",
    tooltip: "名称最多显示6个字符"
  },
  {
    label: "商品图片",
    width: 120,
    prop: "iconimage",
    valueType: "img",
    tooltip: "上传商品图片"
  },
  {
    label: "介绍图片",
    width: 120,
    prop: "images",
    valueType: "img",
    tooltip: "上传商品图片"
  },
  {
    label: "支付类型",
    prop: "payType",
    valueType: "checkbox",
    options: [
      {
        label: "余额",
        value: 0
      },
      {
        label: "收益",
        value: 1
      },
      {
        label: "积分",
        value: 2
      },
      {
        label: "消费券",
        value: 3
      }
    ]
  },
  {
    label: "价格",
    width: 120,
    prop: "money",
    valueType: "input",
    tooltip: "产品价格"
  },
  {
    label: "PV值",
    width: 120,
    prop: "pv",
    valueType: "input"
  },
  {
    label: "释放值",
    width: 120,
    prop: "sf",
    valueType: "input"
  },
  {
    label: "回报值",
    width: 120,
    prop: "hbz",
    valueType: "input"
  },
  {
    label: "上机时间",
    prop: "sjType",
    valueType: "radio",
    options: [
      {
        label: "根据下单时间",
        value: 1
      },
      {
        label: "根据签章时间",
        value: 2
      }
    ]
  },
  {
    label: "上机时间",
    width: 120,
    prop: "sjsj",
    valueType: "input-number",
    fieldProps: { precision: 0, step: 1, min: 0 }
  },
  {
    label: "最低起购",
    width: 120,
    prop: "num",
    valueType: "input-number",
    fieldProps: { precision: 0, step: 1, min: 1 }
  },
  {
    label: "台数",
    width: 120,
    prop: "tai",
    valueType: "input-number",
    fieldProps: { precision: 0, step: 1, min: 0 }
  },
  {
    label: "减少释放%",
    width: 120,
    prop: "minsale",
    valueType: "input-number",
    fieldProps: { precision: 2, step: 1, min: 0 }
  },
  {
    label: "限购",
    width: 120,
    prop: "xg",
    valueType: "input-number",
    fieldProps: { precision: 0, step: 1, min: 0 }
  },
  {
    label: "产品详情",
    width: 120,
    prop: "content",
    tooltip: "产品详情html"
  },
  {
    label: "是否发布",
    prop: "status",
    valueType: "radio",
    options: [
      {
        label: "下架",
        value: "0"
      },
      {
        label: "上架",
        value: "1"
      },
      {
        label: "预售",
        value: "2"
      }
    ]
  },
  {
    label: "是否发货",
    prop: "isShip",
    valueType: "radio",
    options: [
      {
        label: "不发货",
        value: 0
      },
      {
        label: "必需发货",
        value: 1
      },
      {
        label: "用户选择发货",
        value: 2
      }
    ]
  }
];

const visible = ref(false);
const values = ref<FieldValues>({});
const props = defineProps({
  type: {
    type: Number,
    default: 1
  },
  add: {
    type: Boolean,
    default: false
  },
  edit: {
    type: Boolean,
    default: false
  },
  delete: {
    type: Boolean,
    default: false
  }
});
const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onSizeChange,
  loadData,
  onCurrentChange
} = useColumns(props.type);

if (!props.delete && !props.edit) {
  columns.pop();
}

function deleteClick(row) {
  ElMessageBox.confirm("是否删除", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    draggable: true,
    type: "error",
    icon: markRaw(Delete),
    callback: async (action: Action) => {
      // 在这里执行删除操作
      if (action === "confirm") {
        console.log("执行删除操作");
        try {
          const params = {
            orderId: row.fgId,
            isDelete: 1
          };
          const res = await setProductInfo(params);
          loadData();
          ElMessage.success("删除成功");
        } catch (error) {
          console.log(error, "error");
        }
      }
    }
  });
}

const imageFile = (path: any) => {
  return path.split(",").map((path: any) => {
    return { url: fixImageUrl(path), name: path.split("/").pop() };
  });
};
const editClick = async row => {
  console.log(
    "%crow===编辑>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  try {
    const res = await getProductInfo(row.fgId);
    res.data.images = res.data.images
      .split(",")
      .map((path: any) => fixImageUrl(path))
      .join(",");
    res.data.payType = JSON.parse(res.data.payType);
    Object.assign(values.value, res.data);
    // values.value = { ...res.data };
    console.log(
      "%cres===>>>",
      "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
      "返回的",
      res,
      values.value
    );
    edit.value = true;
    visible.value = true;
  } catch (error) {
    console.log(error, "error");
  }
};
const addProduct = () => {
  console.log("%c点击了添加商品>>>: ", "color: MidnightBlue; font-size: 20px;");
  edit.value = false;
  values.value = {};
  visible.value = true;
};
const confirmLoading = ref(false);
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  console.log("value submit", updatedValues);
  const newContent = updatedValues.content.replace(
    /width="(?:auto|\d+)"/g,
    'width="100%"'
  );

  confirmLoading.value = true;
  updatedValues.content = newContent;
  if (!updatedValues.docTemplateId) {
    updatedValues.docTemplateId = "";
  }
  if (!updatedValues.contractUrl) {
    updatedValues.contractUrl = "";
  }
  if (edit.value) {
    try {
      await setProductInfo(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      updatedValues.type = props.type;
      updatedValues.maxsale = 0;
      await addProductInfo(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};
const handleIconImageSuccess: UploadProps["onSuccess"] = (res, file) => {
  console.log("iconsucc", "color: MidnightBlue; font-size: 20px;", file, res);
  values.value.iconimage = res.data;
};
const handleIconImageRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.iconimage = undefined;
  console.log(
    "%cfile===>>>",
    "color: MidnightBlue; font-size: 20px;",
    file,
    files
  );
};
/// 超出limit限制 先清空文件列表再执行上传
const handleIconImageExceed: UploadProps["onExceed"] = files => {
  productImageRef.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  productImageRef.value?.handleStart(file);
  productImageRef.value?.submit();
};
const handlePreviewImage: UploadProps["onPreview"] = file => {
  previewImageName.value = file.name;
  previewImageUrl.value = file.url;
  showPreviewImage.value = true;
};

const handleImagesSuccess: UploadProps["onSuccess"] = (res, file) => {
  console.log(
    "%cfile===>>>",
    "color: MidnightBlue; font-size: 20px;",
    file,
    res
  );
  if (res.code != 0) {
    ElMessage.error(res.msg);
    return;
  }
  const image = res.data;
  if (!values.value.images || values.value.images.length == 0) {
    values.value.images = image;
  } else {
    values.value.images += `,${image}`;
  }
};
const handleImagesRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.images = files.map(item => item.url).join(",");
  console.log("imagesRemove", values.value.images, file, files);
};
/// 超出limit限制 先清空文件列表再执行上传
const handleImagesExceed: UploadProps["onExceed"] = files => {
  ElMessage.error("最多上传5张图片");
  // productImageRef.value?.clearFiles();
  // const file = files[0] as UploadRawFile;
  // file.uid = genFileId();
  // productImageRef.value?.handleStart(file);
  // productImageRef.value?.submit();
};

const imageList = computed(() => {
  const images = values.value.images as string;
  if (images && images.length > 0) {
    return imageFile(images);
  }
  return [];
});

const formRef = ref();
</script>

<template>
  <div class="flex flex-col">
    <div v-if="props.add" class="flex flex-row items-end justify-end mb-4">
      <el-button type="primary" @click="addProduct">
        <el-icon :size="15" color="#fff">
          <IconifyIconOffline :icon="Plus" />
        </el-icon>
        添加商品
      </el-button>
    </div>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      :adaptive="!isMobile"
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columns"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #iconimage="{ row, index }">
        <el-image
          preview-teleported
          loading="lazy"
          :src="fixImageUrl(row.iconimage)"
          :preview-src-list="dataList.map(v => fixImageUrl(v.iconimage))"
          :initial-index="index"
          fit="cover"
          class="w-[50px] h-[50px]"
        />
      </template>
      <template #images="{ row }">
        <div class="flex flex-row flex-wrap gap-2">
          <el-image
            v-for="item in row.images.split(',')"
            :key="item.id"
            preview-teleported
            loading="lazy"
            :src="fixImageUrl(item)"
            :preview-src-list="row.images.split(',').map(v => fixImageUrl(v))"
            fit="cover"
            class="w-[50px] h-[50px]"
          />
        </div>
      </template>
      <template #status="{ row }">
        <el-tag v-if="row.status == '1'" type="success">上架</el-tag>
        <el-tag v-else-if="row.status == '2'" type="info">预售</el-tag>
        <el-tag v-else type="danger">下架</el-tag>
      </template>
      <template #operation="{ row }">
        <div class="flex-col gap-1 flex">
          <el-button
            v-if="props.edit"
            type="primary"
            size="small"
            @click="editClick(row)"
            >编辑</el-button
          >
          <el-button
            v-if="props.delete"
            type="danger"
            size="small"
            @click="deleteClick(row)"
          >
            删除
          </el-button>
        </div>
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading, width: isMobile ? '80%' : '60%' }"
      :title="edit ? '编辑商品' : '添加商品'"
      @confirm="handleSubmit"
    >
      <template #plus-field-iconimage>
        <el-upload
          ref="productImageRef"
          drag
          :auto-upload="true"
          list-type="picture-card"
          :limit="1"
          :http-request="handleImagesUpload"
          :file-list="
            values.iconimage && values.iconimage.length > 0
              ? imageFile(values.iconimage)
              : []
          "
          :on-success="handleIconImageSuccess"
          :on-remove="handleIconImageRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleIconImageExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>

      <template #plus-field-images>
        <el-upload
          ref="productJSImageRef"
          drag
          :auto-upload="true"
          :http-request="handleImagesUpload"
          list-type="picture-card"
          :limit="5"
          :file-list="imageList"
          :on-success="handleImagesSuccess"
          :on-remove="handleImagesRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleImagesExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>
      <template #plus-field-content>
        <div class="wangeditor">
          <Toolbar
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
            style="border-bottom: 1px solid #ccc"
          />
          <Editor
            v-model="values.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            style="height: 500px; overflow-y: hidden"
            @onCreated="handleCreated"
          />
        </div>
      </template>
    </PlusDialogForm>
    <el-dialog v-model="showPreviewImage">
      <img w-full :src="previewImageUrl" :alt="previewImageName" />
    </el-dialog>
  </div>
</template>

<style scoped></style>
